var merge = function(intervals) {

  let ans = [];
  intervals.sort((a, b) => a[0] - b[0]);


  for (let i = 0; i < intervals.length; i++) {
    let cur = intervals[i], j = i + 1;

    while (j < intervals.length && cur[1] >= intervals[j][0]) {
      cur[1] = Math.max(intervals[j][1], cur[1]);
      j++;
    }
    ans.push(cur);
    i = j - 1;
  }
    
  return ans;
};

const intervals = [[1,3],[2,6],[8,10],[15,18]];
console.log(merge(intervals))